//
//  TFLocationHandler.m
//  TFFoundation
//
//  Created by TFAppleWork-Summer on 2017/7/14.
//  Copyright © 2017年 TFAppleWork-Summer. All rights reserved.
//

#import "TFLocationHandler.h"
#import "TFDefine.h"

@interface TFLocationHandler ()<CLLocationManagerDelegate>

@property (nonatomic, strong, readwrite) CLLocation *location;

@property (nonatomic, strong) CLGeocoder *geoCoder;

@property (nonatomic, strong) CLLocationManager *locationManager;

@property (nonatomic, copy) TFLocationHandlerLocationResultBlock locationResultBlock;

@property (nonatomic, copy) TFLocationHandlerLocationAndGeoResultBlock locationAndGeoResultBlock;

@end

@implementation TFLocationHandler

- (void)restartLocate {
    [self.locationManager startUpdatingLocation];
}

- (void)startLocateWithResult:(TFLocationHandlerLocationResultBlock)resultBlock {
    _locationResultBlock = resultBlock;
    [self.locationManager startUpdatingLocation];
}

- (void)startLocateAndGetGeoResult:(TFLocationHandlerLocationAndGeoResultBlock)geoResultBlock {
    _locationAndGeoResultBlock = geoResultBlock;
    [self.locationManager startUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    TFLog(@"locate success:%@",locations);
    //保存当前位置信息
    CLLocation *newLocation = [locations lastObject];
    if (CLLocationCoordinate2DIsValid(newLocation.coordinate)) {
        BOOL equal = [self p_compareOldLocation:_location newLocation:newLocation];
        //判断两个点是否相等，不相等才传递数据，避免重复。
        if (!equal) {
            self.location = [locations lastObject];
            [manager stopUpdatingLocation];
            if (_locationResultBlock) {
                _locationResultBlock(self.location,nil);
                _locationResultBlock = nil;
            }
            if (_locationAndGeoResultBlock) {
                //开始反编码解析
                weakify(self);
                [self.geoCoder reverseGeocodeLocation:self.location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
                    strongify(self);
                    if (error) {
                        if (self.locationAndGeoResultBlock) {
                            self.locationAndGeoResultBlock (nil,nil,error);
                        }
                        self.location = nil;
                        TFLog(@"GeocodeFail:%@",error);
                    }
                    else {
                        CLPlacemark *placemark = [placemarks lastObject];
                        TFLog(@"GeocodeSuccess:%@",placemark);
                        if (self.locationAndGeoResultBlock) {
                            self.locationAndGeoResultBlock (self.location,placemark,nil);
                        }
                    }
                }];
            }
        }
        else {
            _locationResultBlock = nil;
        }
    }
    
}

- (BOOL)p_compareOldLocation:(CLLocation *)oldLocation newLocation:(CLLocation *)newLocation {
    CLLocationDegrees oldLat = (floor(oldLocation.coordinate.latitude*100.0))/100.0;
    CLLocationDegrees oldLon = (floor(oldLocation.coordinate.longitude*100.0))/100.0;
    CLLocationDegrees newLat = (floor(newLocation.coordinate.latitude*100.0))/100.0;
    CLLocationDegrees newLon = (floor(newLocation.coordinate.longitude*100.0))/100.0;
    return (oldLat==newLat&&oldLon==newLon);
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    TFLog(@"locate fail:%@",error);
    if (_locationResultBlock) {
        _locationResultBlock(nil,error);
    }
    if (_locationAndGeoResultBlock) {
        _locationAndGeoResultBlock(nil,nil,error);
    }
}

#pragma mark - lazy load.

- (CLLocationManager *)locationManager {
    if (!_locationManager) {
        _locationManager = [[CLLocationManager alloc] init];
        _locationManager.delegate = self;
        _locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
        _locationManager.distanceFilter = 100.0;
        [_locationManager requestWhenInUseAuthorization];
    }
    return _locationManager;
}

- (CLGeocoder *)geoCoder {
    if (!_geoCoder) {
        _geoCoder = [[CLGeocoder alloc] init];
    }
    return _geoCoder;
}

- (void)dealloc {
    TFLog(@"");
    
}

@end
